package com.spyx.payment.controller;


import com.atyx.spyx.enums.PaymentType;
import com.spyx.payment.service.PaymentInfoService;
import com.spyx.payment.service.WeiXinService;
import com.spyx.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/payment")
public class WeiXinController {

    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private PaymentInfoService paymentInfoService;
    //获取微信支付信息（创建预付单）
    @GetMapping("weixin/createJsapi/{orderNo}")
    public Result createJsapi(@PathVariable("orderNo")String orderNo) throws Exception {
        //创建预付单，返回的map中封装和二维码相关的信息
        Map<String ,String> result=  weiXinService.createJsapi(orderNo);
        return Result.ok(result);
    }

    //查询订单状态
    @GetMapping("weixin/queryPayStatus/{orderNo}")
    public Result queryPayStatus(@PathVariable("orderNo")String orderNo){
        //1.调取微信支付端的接口，查看订单的支付状态
        Map resultMap=weiXinService.queryPayStatus(orderNo, PaymentType.WEIXIN.name());
        //2.支付失败
        if(resultMap==null){
            return Result.fail("支付错误");
        }
        //3.支付成功  resultMap有值，但是不代表支付成功
        //if("SUCCESS".equals(resultMap.get("trade_state"))){
        if(resultMap!=null){
                //支付成功
             //3.1 更新订单的支付状态   3.2 更新payment_info表中支付状态  3.3 扣减库存
            //更新payment_info表时需要trade_no（交易编号）。这个交易编号从resultMap中获取
            paymentInfoService.paySuccess(orderNo,PaymentType.WEIXIN,resultMap);
            return Result.ok("支付成功");
        }

        return Result.ok("支付中");
    }
}
